package com.example.black.myapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class PaletteView extends View {
    private Paint paint;
    private Path path;
    private Bitmap bitmap;
    private Canvas mCanvas;
    private float mLastX;
    private float mLastY;
    public PaletteView(Context context) {
        this(context,null);
    }

    public PaletteView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public PaletteView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG );
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(getResources().getColor(R.color.colorAccent));
        paint.setFilterBitmap(true);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(20);
    }

    private void initBuffer(){
        bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(bitmap);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        if (bitmap != null) {
            canvas.drawBitmap(bitmap, 0, 0, null);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int action = event.getAction() & MotionEvent.ACTION_MASK;
        final float x = event.getX();
        final float y = event.getY();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastX = x;
                mLastY = y;
                if (path == null) {
                    path = new Path();
                }
                path.moveTo(x,y);
                break;
            case MotionEvent.ACTION_MOVE:
                //这里终点设为两点的中心点的目的在于使绘制的曲线更平滑，如果终点直接设置为x,y，效果和lineto是一样的,实际是折线效果
                //path.quadTo(mLastX, mLastY, (x + mLastX) / 2, (y + mLastY) / 2);
                path.lineTo(x,y);
                if (bitmap == null) {
                    initBuffer();
                }

                mCanvas.drawPath(path,paint);
                //图形失效重绘
                invalidate();
                mLastX = x;
                mLastY = y;
                break;
            case MotionEvent.ACTION_UP:

                path.reset();
                break;
        }
        return true;
    }
    public void clear(){
        bitmap.eraseColor(Color.TRANSPARENT);
    }

    public Bitmap getBitmap() {
        return bitmap;
    }
}
